package cn.kickegg.concurrent.collections.list;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * CopyOnWriteArrayLists 这个类和ArrayList最大的区别就是add(E) 的时候。容器会自动copy一份出来然后再尾部add(E)
 * CopyOnWriteArrayList适合使用在读操作远远大于写操作的场景里，比如缓存。发生修改时候做copy，新老版本分离，保证读的高性能，适用于以读为主的情况。
 * 源码:
 * /**
 * Appends the specified element to the end of this list.
 *
 * @param e element to be appended to this list
 * @return <tt>true</tt> (as specified by {@link Collection#add})

public boolean add(E e) {
final ReentrantLock lock = this.lock;
        lock.lock();
        try {
        Object[] elements = getArray();
        int len = elements.length;
        Object[] newElements = Arrays.copyOf(elements, len + 1);
        newElements[len] = e;
        setArray(newElements);
        return true;
        } finally {
        lock.unlock();
        }
        }
 */
public class CopyOnWriteArrayLists {

    public static void main(String[] args) {
        Set list=new CopyOnWriteArraySet();//ArrayList有异常
        list.add("1");
        list.add("1");
        list.add("3");
        list.add("4");
        Iterator<String> iterator= list.iterator();
        while(iterator.hasNext()){
            String key= iterator.next();
            System.out.println(key);
            if(key.equals("3")){
                list.add("5");
                list.remove("1");
//                list.set(1,"2");
//                list.
            }


        }

    }

}
